import bpy
import os
from urllib.parse import quote

# 定义全局变量 plugin_path
plugin_path = os.path.dirname(os.path.abspath(__file__))
if not plugin_path.endswith(os.sep):
    plugin_path += os.sep

bl_info = {
    "name": "翻译存储插件",
    "author": "空想幻灵",
    "version": (1, 0),
    "blender": (3, 0, 0),
    "location": "属性面板",
    "description": "将翻译词条保存到 PO 文件的插件",
    "warning": "",
    "doc_url": "",
    "category": "翻译"
}

# 修改: get_po_path 函数，确保返回的路径是基于文件夹路径拼接文件名生成的完整路径
def get_po_path(context):
    if context.scene.po_filepath:
        po_dir = os.path.dirname(context.scene.po_filepath) if os.path.isfile(context.scene.po_filepath) else context.scene.po_filepath
        if not po_dir.endswith(os.sep):
            po_dir += os.sep
        language_name = context.scene.language_name
        plugin_name = context.scene.plugin_name
        author_name = context.scene.author_name
        new_filename = f"{language_name}666{plugin_name}666{author_name}.po"
        po_path = os.path.join(po_dir, new_filename)
    else:
        # 如果没有指定路径，则使用插件路径
        language_name = context.scene.language_name
        plugin_name = context.scene.plugin_name
        author_name = context.scene.author_name
        new_filename = f"{language_name}666{plugin_name}666{author_name}.po"
        po_path = os.path.join(plugin_path, new_filename)
    
    return po_path

class SaveTranslationOperator(bpy.types.Operator):
    """保存词条到PO文件"""
    bl_idname = "object.save_translation"
    bl_label = "保存词条"

    def execute(self, context):
        # 直接使用场景属性中的路径或回退生成路径
        # 优先使用已打开文件的路径
        if context.area.type == 'TEXT_EDITOR' and context.space_data.text:
            current_path = context.space_data.text.filepath
            context.scene.po_filepath = os.path.dirname(current_path)
            po_path = get_po_path(context)
        else:
            if context.scene.po_filepath and os.path.isfile(context.scene.po_filepath):
                po_path = context.scene.po_filepath
            else:
                po_path = get_po_path(context)
                context.scene.po_filepath = os.path.dirname(po_path)

        # 确保文件存在，如果不存在则创建文件并写入初始内容
        if not os.path.exists(po_path):
            with open(po_path, 'w', encoding='utf-8') as f:
                f.write(f'msgid "{context.scene.msgid}"\n')
                f.write(f'msgstr "{context.scene.msgstr}"\n')
        
        # 打开或切换到文本编辑器并加载文件
        if context.area.type != 'TEXT_EDITOR' or not context.space_data.text:
            bpy.ops.text.open(filepath=po_path)
        else:
            # 如果当前已打开其他文件，则切换到目标文件
            for text in bpy.data.texts:
                if text.filepath == po_path:
                    context.space_data.text = text
                    break
            else:
                bpy.ops.text.open(filepath=po_path)
        
        # 更新文件内容
        try:
            with open(po_path, 'r+', encoding='utf-8') as f:
                lines = f.readlines()
                found = False
                for i in range(len(lines)):
                    if lines[i].strip() == f'msgid "{context.scene.msgid}"':
                        if i+1 < len(lines) and lines[i+1].startswith('msgstr'):
                            lines[i+1] = f'msgstr "{context.scene.msgstr}"\n'
                            found = True
                            break
                if not found:
                    lines.append(f'\nmsgid "{context.scene.msgid}"\n')
                    lines.append(f'msgstr "{context.scene.msgstr}"\n')
                f.seek(0)
                f.writelines(lines)
                f.truncate()
        except FileNotFoundError:
            with open(po_path, 'w', encoding='utf-8') as f:
                f.write(f'msgid "{context.scene.msgid}"\n')
                f.write(f'msgstr "{context.scene.msgstr}"\n')
        
        # 确保有活动的文本编辑器并且有打开的PO文件
        if context.area.type == 'TEXT_EDITOR' and context.space_data.text:
            # 触发从磁盘重新加载
            bpy.ops.text.reload()

        return {'FINISHED'}

class TextEditorPanel(bpy.types.Panel):
    bl_label = 'PO文件管理'
    bl_idname = 'TEXT_EDITOR_PT_po_management'
    bl_space_type = 'TEXT_EDITOR'
    bl_region_type = 'UI'

    def draw(self, context):
        layout = self.layout
        scene = context.scene
        layout.prop(scene, 'po_filepath', text="PO存储路径")
        layout.prop(scene, 'language_name', text="语言名")
        layout.prop(scene, 'plugin_name', text="插件名")
        layout.prop(scene, 'author_name', text="作者名")
        # 绑定当前文本对象
        if context.space_data and context.space_data.text:
            text = context.space_data.text
            layout.prop(text, "name", text="当前文件")
        layout.prop(scene, 'msgid')
        layout.prop(scene, 'msgstr')
        layout.operator('text.open_po_file', text='打开PO文件')
        layout.operator('object.save_translation', text='保存词条')
        layout.operator('object.send_email', text='发送到管理员的邮箱')


class OpenPOFileOperator(bpy.types.Operator):
    bl_idname = 'text.open_po_file'
    bl_label = '打开PO文件'
    
    filepath: bpy.props.StringProperty(subtype="FILE_PATH")
    filter_glob: bpy.props.StringProperty(default="*.po", options={'HIDDEN'})

    def execute(self, context):
        po_path = self.filepath
        if os.path.exists(po_path):
            # 解析文件名获取字段信息
            filename = os.path.basename(po_path).replace('.po', '')
            if '666' in filename:
                parts = filename.split('666')
                if len(parts) == 3:
                    context.scene.language_name = parts[0]
                    context.scene.plugin_name = parts[1]
                    context.scene.author_name = parts[2]
            
            bpy.ops.text.open(filepath=po_path)
            context.scene.po_filepath = os.path.dirname(po_path)
            # 强制刷新文本编辑器界面
            if context.area:
                context.area.tag_redraw()
        return {'FINISHED'}
    
    def invoke(self, context, event):
        # 使用全局变量 plugin_path
        self.filepath = plugin_path
        context.window_manager.fileselect_add(self)
        return {'RUNNING_MODAL'}

class SendEmailOperator(bpy.types.Operator):
    bl_idname = "object.send_email"
    bl_label = "联系管理员"

    def execute(self, context):
        current_file = context.space_data.text.name if context.space_data and context.space_data.text else '未命名文件'
        subject = f"{current_file}-翻译提交请求" if current_file != '未命名文件' else "新翻译提交请求"
        body_text = f'请添加{current_file}为附件' if current_file != '未命名文件' else '请添加字典文件'
        subject_encoded = quote(subject)
        body_encoded = quote(body_text)
        mailto_url = f"mailto:1058766327@qq.com?subject={subject_encoded}&body={body_encoded}"
        os.startfile(mailto_url)
        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

def register():
    bpy.utils.register_class(SaveTranslationOperator)
    bpy.utils.register_class(TextEditorPanel)
    bpy.utils.register_class(OpenPOFileOperator)
    
    
    # 注册场景属性
    bpy.types.Scene.language_name = bpy.props.StringProperty(name="语言名", default="中")
    bpy.types.Scene.plugin_name = bpy.props.StringProperty(name="插件名", default="插件名")
    bpy.types.Scene.author_name = bpy.props.StringProperty(name="作者名", default="作者名")
    bpy.types.Scene.msgid = bpy.props.StringProperty(name="原文", default="Add")
    bpy.types.Scene.msgstr = bpy.props.StringProperty(name="译文", default="添加")
    bpy.types.Scene.po_filepath = bpy.props.StringProperty(name="PO文件路径", subtype='FILE_PATH')
    bpy.utils.register_class(SendEmailOperator)        

def unregister():
    bpy.utils.unregister_class(SaveTranslationOperator)
    bpy.utils.unregister_class(TextEditorPanel)
    bpy.utils.unregister_class(OpenPOFileOperator)
    
    bpy.utils.unregister_class(SendEmailOperator)
    # 移除场景属性
    del bpy.types.Scene.language_name
    del bpy.types.Scene.plugin_name
    del bpy.types.Scene.author_name
    del bpy.types.Scene.msgid
    del bpy.types.Scene.msgstr
    del bpy.types.Scene.po_filepath

if __name__ == "__main__":
    register()